<?php

namespace app\admin\controller\ai;

use app\common\controller\Backend;
use think\Db;

/**
 * AI检测报告
 *
 * @icon fa fa-circle-o
 */
class Ai extends Backend
{

    /**
     * Ai模型对象
     * @var \app\admin\model\ai\Ai
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ai\Ai;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function aiget()
    {
        // 生成UUID（需要安装php-uuid扩展）
        $uuid = 1741681363321;//1728805784871;//uuid_create(UUID_TYPE_RANDOM);

        // 目标API地址
        $apiUrl = 'https://yayi-zy-renhe.wengegroup.com/zy/app/share/records/query_encrypt/1741681363321';//'http://yayi-zy-renhe-yfb.wengegroup.com/zy/app/share/records/query_encrypt/1731141399823 ';
        $requestUrl = $apiUrl . '?uuid=' . urlencode($uuid);

        // 初始化cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $requestUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
            ]
        ]);

        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        // 处理响应
        if ($error) {
            die("cURL Error: " . $error);
        }

        if ($httpCode != 200) {
            die("HTTP Error: Status code {$httpCode}");
        }

        // 解析JSON数据
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            die("JSON Parse Error: " . json_last_error_msg());
        }

        // 使用返回数据
        $data = $data['data']['encryptedData'];
       
        $key = $this->aigetkey();

        $data = $this->aesDecrypt($data,$key);

        $indata = [
                 'uuid'=> $uuid,
                 'jdata'=>$data,
                 'createtime'=>time()
        ];

        $info_id= Db::name('ai_info')->insertGetId($indata);

       
        var_dump($info_id);

        $data = json_decode($data, true);
    
        var_dump($data['appRecordsDTO']['createDate']);
        var_dump($data['appRecordsDTO']);
        var_dump(strtotime($data['appRecordsDTO']['createDate']));
        var_dump($data['operatorsRecordsDTO']);

        $aidata = [
            'info_id' =>$info_id,
            'uuid'=> $uuid,
            'name'=>$data['appRecordsDTO']['realName'],
            'gender'=>$data['appRecordsDTO']['gender'],
            'mobile'=>$data['appRecordsDTO']['telephone'],
            'level'=>$data['appRecordsDTO']['age'],
            'worktime'=>strtotime($data['appRecordsDTO']['createDate']),
            'shopname'=>$data['operatorsRecordsDTO']['storeName'], //缺少门店名称
            'work'=>$data['operatorsRecordsDTO']['manager'],
            'url'=>"https://yayi-zy-renhe.wengegroup.com/zy/app/minio/download?cache=true&file_name=".$data['appRecordsDTO']['reportUrl'],
            'createtime'=>time()
        ];

        $info_id= Db::name('ai')->insertGetId($aidata);

    }

    public function ailist()
    {
        // 生成UUID（需要安装php-uuid扩展）
        $uuid = 1728805784871;//uuid_create(UUID_TYPE_RANDOM);

        // 目标API地址
        $apiUrl = 'https://yayi-zy-renhe.wengegroup.com/zy/app/share/records/query';//'http://yayi-zy-renhe-yfb.wengegroup.com/zy/app/share/records/query_encrypt/1731141399823 ';
        $requestUrl = $apiUrl;
        $postData = [                      // 定义请求参数（键值对）
            'page' => 1,
            'page_size' => 10,
            'start_date' => '2025-03-01 00:00:00',
            'end_date' =>''
        ];
        $postData = json_encode($postData);
        // 初始化cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $requestUrl,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => $postData,
           // CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json',
                
            ]
        ]);

        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        // 处理响应
        if ($error) {
            die("cURL Error: " . $error);
        }

        if ($httpCode != 200) {
            die("HTTP Error: Status code {$httpCode}");
        }

        // 解析JSON数据
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            die("JSON Parse Error: " . json_last_error_msg());
        }

        // 使用返回数据
        $data = $data['data'];
       
        $key = $this->aigetkey();

        $data = $this->aesDecrypt($data,$key);

        var_dump($data);

        // $indata = [
        //          'uuid'=> $uuid,
        //          'jdata'=>$data,
        //          'createtime'=>time()
        // ];

        // $info_id= Db::name('ai_info')->insertGetId($indata);

       
        // var_dump($info_id);

        // $data = json_decode($data, true);
    
        // var_dump($data['appRecordsDTO']['createDate']);
        // var_dump($data['appRecordsDTO']);
        // var_dump(strtotime($data['appRecordsDTO']['createDate']));
        // var_dump($data['operatorsRecordsDTO']);

        // $aidata = [
        //     'info_id' =>$info_id,
        //     'uuid'=> $uuid,
        //     'name'=>$data['appRecordsDTO']['realName'],
        //     'gender'=>$data['appRecordsDTO']['gender'],
        //     'mobile'=>$data['appRecordsDTO']['telephone'],
        //     'level'=>$data['appRecordsDTO']['age'],
        //     'worktime'=>strtotime($data['appRecordsDTO']['createDate']),
        //     'shopname'=>$data['operatorsRecordsDTO']['storeName'], //缺少门店名称
        //     'work'=>$data['operatorsRecordsDTO']['manager'],
        //     'url'=>"https://yayi-zy-renhe.wengegroup.com/zy/app/minio/download?cache=true&file_name=".$data['appRecordsDTO']['reportUrl'],
        //     'createtime'=>time()
        // ];

        // $info_id= Db::name('ai')->insertGetId($aidata);

    }
  
    public function aigetkey()
    {


        // 目标API地址
        $apiUrl = 'https://yayi-zy-renhe.wengegroup.com/zy/app/records/query_key';
        $requestUrl = $apiUrl;

        // 初始化cURL
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $requestUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
            ]
        ]);

        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);

        // 处理响应
        if ($error) {
            die("cURL Error: " . $error);
        }

        if ($httpCode != 200) {
            die("HTTP Error: Status code {$httpCode}");
        }

        // 解析JSON数据
        $data = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            die("JSON Parse Error: " . json_last_error_msg());
        }

        // 使用返回数据
        // var_dump($data['data']);

        return $data['data'];

    }

    /**
     * AES-256-CBC模式解密（兼容PKCS7填充）
     * 
     * @param string $encryptedData 待解密数据（base64编码字符串）
     * @param string $key           加密密钥（32字节长度）
     * @param string $iv            初始化向量（16字节长度）
     * 
     * @return string|bool 解密后的明文，失败返回false
     */
    public function aesDecrypt($encryptedData, $key)
    {
        // Base64解码
        $ciphertext = base64_decode($encryptedData);


        // 执行解密
        $decrypted = openssl_decrypt(
            $ciphertext,
            'aes-256-ecb',
            $key,
            OPENSSL_RAW_DATA,
           
        );

        return $decrypted !== false ? $decrypted : false;
    }

}
